﻿using Furion.SensitiveDetection;

namespace Admin.NET.Core;

/// <summary>
/// 打印模板配置
/// </summary>
[ApiDescriptionSettings(Order = 306)]
public class PrintDevService : IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储
    /// </summary>
    private readonly SqlSugarRepository<SysPrintTemplate> _sysPrintTemplateRep;

    /// <summary>
    /// 脱敏词汇提供器.
    /// </summary>
    private readonly ISensitiveDetectionProvider _sensitiveDetectionProvider;

    public PrintDevService(SqlSugarRepository<SysPrintTemplate> sysPrintTemplateRep, ISensitiveDetectionProvider sensitiveDetectionProvider)
    {
        _sysPrintTemplateRep = sysPrintTemplateRep;
        _sensitiveDetectionProvider = sensitiveDetectionProvider;
    }

    /// <summary>
    /// 分页查询打印模板2
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询打印模板2")]
    public async Task<SqlSugarPagedList<PrintDevOutput>> Page(PageSysPrintTemplateInput input)
    {
        input.SearchKey = input.SearchKey?.Trim();
        var query = _sysPrintTemplateRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.Name.Contains(input.SearchKey)
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.Name), u => u.Name.Contains(input.Name.Trim()))
            .WhereIF(input.EnabledMark > 0, u => u.EnabledMark == input.EnabledMark)
            .Select<PrintDevOutput>();
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加打印模板2
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加打印模板2")]
    public async Task<long> Add(AddSysPrintTemplateInput input)
    {
        var entity = input.Adapt<SysPrintTemplate>();
        await _sysPrintTemplateRep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除打印模板2
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除打印模板2")]
    public async Task Delete(DeleteSysPrintTemplateInput input)
    {
        var entity = await _sysPrintTemplateRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _sysPrintTemplateRep.FakeDeleteAsync(entity);   //假删除
        //await _sysPrintTemplateRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新打印模板2
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新打印模板2")]
    public async Task Update(UpdateSysPrintTemplateInput input)
    {
        var entity = input.Adapt<SysPrintTemplate>();
        await _sysPrintTemplateRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取打印模板2
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取打印模板2")]
    public async Task<SysPrintTemplate> Detail([FromQuery] QueryByIdSysPrintTemplateInput input)
    {
        return await _sysPrintTemplateRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取打印模板2列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取打印模板2列表")]
    public async Task<List<PrintDevOutput>> List([FromQuery] PageSysPrintTemplateInput input)
    {
        return await _sysPrintTemplateRep.AsQueryable().Select<PrintDevOutput>().ToListAsync();
    }

    /// <summary>
    /// 表单字段.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("Fields")]
    public async Task<dynamic> GetFields([FromBody] PrintDevFieldsQuery input)
    {
        if (input.sqlTemplate.IsNullOrEmpty() && !(await _sensitiveDetectionProvider.VaildedAsync(input.sqlTemplate.ToUpper())))
            throw Oops.Oh(ErrorCodeEnum.xg1005);

        //var link = await _dbLinkService.GetInfo(input.dbLinkId);
        //var tenantLink = link ?? _dataBaseManager.GetTenantDbLink(_userManager.TenantId, _userManager.TenantDbName);
        //if (!_dataBaseManager.IsConnection(tenantLink)) throw Oops.Oh(ErrorCode.D1507);

        var parameter = new List<SugarParameter>()
        {
            new SugarParameter("@formId", null)
        };
        var sqlList = input.sqlTemplate.ToList<PrintDevSqlModel>();
        var output = new List<PrintDevFieldModel>();
        var index = 0;
        foreach (var item in sqlList)
        {
            if (item.sql.IsNullOrEmpty())
                throw Oops.Oh(ErrorCodeEnum.xg1002);
            //var dataTable = _dataBaseManager.GetSqlData(tenantLink, item.sql, false, parameter.ToArray());

            //var fieldModel = new PrintTemplateFieldModel()
            //{
            //    id = index == 0 ? "headTable" : "childrenDataTable" + (index - 1),
            //    parentId = "struct",
            //    fullName = index == 0 ? "主表" : "子表" + (index - 1),
            //};
            //output.Add(fieldModel);
            //output.AddRange(GetFieldModels(dataTable, fieldModel));
            //++index;
        }
        return output.ToTree("struct");
    }
}